package com.tydh.webservice.common.utils;

import com.tydh.webservice.bean.ParamSettingBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Component
public class AllSetParam {

    @Autowired
    private ParamSettingBean paramSettingBean;

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public  String getBaseParamsByBean(Object obj){
        StringBuilder sb = new StringBuilder();
        Class clazz = obj.getClass();
        Field[] fields = obj.getClass().getDeclaredFields();//获得属性
        try{
            for (Field field : fields) {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
                        clazz);
                Method getMethod = pd.getReadMethod();//获得get方法
                Object o = getMethod.invoke(obj);//执行get方法返回一个Object
                log.info("得到的返回值是:{}", o);
                sb.append(o.toString());
            }
        }catch (Exception e){
            log.info("参数设置错误:{}", e.getMessage());
        }

        return sb.toString();
    }

    public  Map setMessageHeader(String baseParams){
        Map<String, String> messageHeader = new HashMap<>();

        messageHeader.put("sysCode", paramSettingBean.getSysCode());
        messageHeader.put("sendDate", dateFormat.format(new Date()));
        messageHeader.put("sign",getSign(paramSettingBean.getPwd(), baseParams));
        messageHeader.put("serialNo", UUID.randomUUID().toString());
        return messageHeader;
    }

    private  String getSign(String password, String... params) {
        StringBuffer sb = new StringBuffer(password);
        if (params != null) {
            for (String o : params) {
                sb.append(o);
            }
        }

        log.info("传递过来的数据是"+sb.toString());
        String mysign = //Base64.encodeBase64String(DigestUtils.md5DigestAsHex(DigestUtils.md5Digest(sb.toString().getBytes())).getBytes());
                Base64.encodeBase64String(MD5.encrypt(MD5.encrypt(sb.toString())).getBytes())
                        .replaceAll("\r|\n", "");

        return mysign;
    }
}
